/* eslint-disable */
const fs = require('fs');
const path = require("path");
// 构建API，生成ts接口
build({
    url: "../../public/apidoc/api_data.json",
    projectName: "myProject",
    saveDir: "../../public/ts"
});

function build(config) {
    const api_data = require(config.url);
    const dir = path.resolve(__dirname, config.saveDir);
    let inputParame = "";
    let outParame = "";
    let apiTs = "";
    Object.entries(divideGroup(api_data)).forEach(([key, value]) => {
        inputParame += buildInputParame(key, value, config);
        apiTs += buildApi(key, value, config);
    });
    createFile(path.resolve(dir, "interfaces", `${config.projectName}.d.ts`), inputParame);//入参生成定义结构
    // createFile(path.resolve(dir, "apis", config.projectName, `${key}.ts`), apiTs);//生成调用方法
}

function buildInputParame(key, value, config) {
    const result = value.map(item => {
        return buildFieldStr(`IInput${item.name}`, item.parameter?.fields?.Parameter, item.title);
    });
    return result.join("\n");
}

function buildApi(key, value, config) {
}


function buildFieldStr(name, fields, description) {
    if (!fields || fields.length === 0) {
        return "";
    }
    const tsFields = fields.map(field => {
        const optional = field.optional ? "?" : "";//是否可选
        let type = field.type;//数据类型解析
        if (type === "Array") {
            type = "any[]";
        } else {
            type = type.toLowerCase();
        }
        let description = "";//补充注释
        if (field.description) {
            description = field.description.replace(/<[^>]*>|<\/[^>]*>/gm, "");//去除html标签
            description = `// ${description}\n`
        }
        return `${description}${field.field}${optional}:${type}`;
    });
    description = `/** \n * ${description} \n */ \n`;
    return `${description} export interface ${name}{\n${tsFields.join(',\n')}\n}`;
}

/**
 * 分组，根据group
 * @param data
 * @return {{}}
 */
function divideGroup(data) {
    const groupedData = {};
    data.forEach(item => {
        const group = item.group;
        if (!groupedData[group]) {
            groupedData[group] = [];
        }
        groupedData[group].push(item);
    });
    return groupedData;
}

/**
 * 创建文件
 * @param filePath 文件路径
 * @param data 数据
 */
function createFile(filePath, data) {
    const parentDirectory = path.dirname(filePath);
    fs.mkdirSync(parentDirectory, {recursive: true});//创建目录
    fs.writeFile(filePath, data, "utf-8", err => {
        err && console.error("文件创建错误", err);
    });
}
